package com.raychi.demo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.raychi.demo.entity.Product;
import com.raychi.demo.util.ProductUtil;

public class ProductDao {
	
	public List<Product> getProducts(Connection conn) throws ClassNotFoundException, SQLException{
		List<Product> products = new ArrayList<Product>();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("select * from product");
		Product product = null;
		while(rs.next()){
			product = ProductUtil.createProduct(rs);
			products.add(product);
		}
		return products;
	}
	
	public void delete(Product product, Connection conn) throws Exception{
		Statement st = conn.createStatement();
		String sql = "delete from product where id=" + product.getId();
		st.execute(sql);
	}
	
	public void update(Product product, Connection conn) throws Exception{
		String sql = "update product set name = ?,price = ? where id = ?"; 	
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, product.getName());
		ps.setFloat(2, product.getPrice());
		ps.setInt(3, product.getId());
		ps.executeUpdate();
	}
	
	public void save(Product product, Connection conn) throws Exception{
		String sql = "insert into product (name,price,catId) values (?,?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, product.getName());
		ps.setFloat(2, product.getPrice());
		ps.setInt(3, product.getCatId());
		ps.execute();
	}
	

}
